document.addEventListener("DOMContentLoaded", function () {
  const chatMessages = document.getElementById("chat-messages");
  const userInput = document.getElementById("user-input");
  const sendButton = document.getElementById("send-btn");
  const minimizeBtn = document.getElementById("minimize-btn");
  const chatContainer = document.querySelector(".chat-container");
  const fileInput = document.getElementById("file-input");
  const uploadBtn = document.getElementById("upload-btn");
  const webSearchToggle = document.getElementById("web-search-toggle");

  let isMinimized = false;
  let currentFile = null;

  function addMessage(message, isUser) {
    const messageDiv = document.createElement("div");
    messageDiv.className = `message ${isUser ? "user-message" : "ai-message"}`;
    messageDiv.textContent = message;
    chatMessages.appendChild(messageDiv);
    chatMessages.scrollTop = chatMessages.scrollHeight;
  }

  function showLoading() {
    const loadingDiv = document.createElement("div");
    loadingDiv.className = "message ai-message loading";
    const dots = document.createElement("div");
    dots.className = "loading-dots";
    dots.innerHTML = "<span></span><span></span><span></span>";
    loadingDiv.appendChild(dots);
    chatMessages.appendChild(loadingDiv);
    chatMessages.scrollTop = chatMessages.scrollHeight;
    return loadingDiv;
  }

  async function uploadFile() {
    const file = fileInput.files[0];
    if (!file) return;

    const formData = new FormData();
    formData.append("file", file);

    try {
      const response = await fetch("/upload", {
        method: "POST",
        body: formData,
      });

      const data = await response.json();
      if (data.success) {
        currentFile = file.name;
        addMessage(`文件上传成功：${file.name}`, false);
        addMessage("请输入您的问题，我会根据上传的文件内容来回答。", false);
      } else {
        addMessage(`文件上传失败：${data.error}`, false);
      }
    } catch (error) {
      console.error("Upload error:", error);
      addMessage("文件上传失败，请检查网络连接", false);
    }
  }

  async function sendMessage() {
    const message = userInput.value.trim();
    if (!message) return;

    // 禁用输入和发送按钮
    userInput.value = "";
    userInput.disabled = true;
    sendButton.disabled = true;

    // 显示用户消息
    addMessage(message, true);

    // 创建AI消息容器
    const aiMessageDiv = document.createElement("div");
    aiMessageDiv.className = "message ai-message";
    chatMessages.appendChild(aiMessageDiv);
    chatMessages.scrollTop = chatMessages.scrollHeight;

    try {
      const response = await fetch("/chat", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          message: message,
          file: currentFile,
        }),
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      await handleStreamResponse(response, aiMessageDiv);
    } catch (error) {
      console.error("Error:", error);
      aiMessageDiv.textContent = "发送消息失败，请检查网络连接";
    } finally {
      // 重新启用输入和发送按钮
      userInput.disabled = false;
      sendButton.disabled = false;
      userInput.focus();
    }
  }

  // 清除文件
  function clearFile() {
    currentFile = null;
    fileInput.value = "";
    addMessage("已清除当前文件", false);
  }

  // 添加文件清除按钮
  const clearFileBtn = document.createElement("button");
  clearFileBtn.id = "clear-file-btn";
  clearFileBtn.textContent = "清除文件";
  clearFileBtn.onclick = clearFile;
  document.querySelector(".file-upload").appendChild(clearFileBtn);

  minimizeBtn.addEventListener("click", () => {
    const chatContent = document.querySelector(".chat-messages");
    const chatInput = document.querySelector(".chat-input");
    const fileUpload = document.querySelector(".file-upload");
    const chatOptions = document.querySelector(".chat-options");

    if (isMinimized) {
      chatContent.style.display = "block";
      chatInput.style.display = "block";
      fileUpload.style.display = "flex";
      chatOptions.style.display = "block";
      minimizeBtn.textContent = "-";
      chatContainer.style.height = "600px";
    } else {
      chatContent.style.display = "none";
      chatInput.style.display = "none";
      fileUpload.style.display = "none";
      chatOptions.style.display = "none";
      minimizeBtn.textContent = "+";
      chatContainer.style.height = "auto";
    }
    isMinimized = !isMinimized;
  });

  uploadBtn.addEventListener("click", uploadFile);
  sendButton.addEventListener("click", sendMessage);

  userInput.addEventListener("keypress", function (e) {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault();
      sendMessage();
    }
  });

  // 添加欢迎消息
  setTimeout(() => {
    addMessage(
      "你好！我是AI智能题目生成系统。我可以：\n1. 根据您的需求生成各类题目\n2. 判断答案正确性\n3. 结合本地知识库和网络搜索生成题目\n\n请上传文件或直接输入您的需求。",
      false
    );
  }, 1000);

  function formatMessage(content) {
    const container = document.createElement("div");
    container.className = "exam-container";

    // 添加工具栏
    const toolbar = document.createElement("div");
    toolbar.className = "toolbar";

    // 添加下载和复制按钮
    toolbar.innerHTML = `
        <button class="download-btn" onclick="downloadExam(this.parentElement.parentElement)">
            <i class="fas fa-download"></i> 下载试卷
        </button>
        <button class="copy-btn" onclick="copyContent(this.parentElement.parentElement)">
            <i class="fas fa-copy"></i> 复制全部
        </button>
    `;

    container.appendChild(toolbar);
    container.innerHTML += content;

    return container;
  }

  async function downloadExam(content) {
    try {
      const response = await fetch("/download-exam", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ content }),
      });

      if (!response.ok) throw new Error("下载失败");

      const data = await response.json();
      if (data.success) {
        window.location.href = `/downloads/${data.filename}`;
      }
    } catch (error) {
      console.error("Download error:", error);
      alert("下载失败，请重试");
    }
  }

  // 处理流式输出
  function handleStreamResponse(response, aiMessageDiv) {
    const reader = response.body.getReader();
    const decoder = new TextDecoder();
    let buffer = "";

    return reader.read().then(function processText({ done, value }) {
      if (done) {
        if (buffer) {
          const container = document.createElement("div");
          container.className = "section";
          container.innerHTML = buffer;
          aiMessageDiv.appendChild(container);
        }
        return;
      }

      const text = decoder.decode(value);
      const lines = text.split("\n");

      for (const line of lines) {
        if (line.startsWith("data: ")) {
          const content = line.slice(6);
          if (content === "[DONE]") {
            break;
          }

          // 创建新的段落容器
          const container = document.createElement("div");
          container.className = "section";
          container.innerHTML = content;
          aiMessageDiv.appendChild(container);

          // 滚动到最新内容
          chatMessages.scrollTop = chatMessages.scrollHeight;
        }
      }

      return reader.read().then(processText);
    });
  }
});
